
package com.hazelcast.internal.config.override;

import javax.annotation.Nonnull;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * A representation of a single generic configuration node.
 * <p>
 * Used while overriding configuration with environment variables/system properties.
 */
class ConfigNode {
    private final ConfigNode parent;
    private final String name;
    private final Map<String, ConfigNode> children = new LinkedHashMap<>();
    private String value;
    private boolean isRead;

    ConfigNode(@Nonnull String name) {
        this(name, null);
    }

    ConfigNode(String name, ConfigNode parent) {
        Objects.requireNonNull(name);
        this.name = name;
        this.parent = parent;
    }

    boolean isRead() {
        return isRead;
    }

    String getName() {
        return name;
    }

    boolean hasValue() {
        return value != null;
    }

    String getValue() {
        isRead = true;
        return value;
    }

    void setValue(String value) {
        this.value = value;
    }

    Map<String, ConfigNode> getChildren() {
        return children;
    }

    Optional<ConfigNode> getParent() {
        return Optional.ofNullable(parent);
    }

    @Override
    public String toString() {
        return String.format("ConfigNode{name='%s', children=%s, value='%s'}", name, children, value);
    }
}
